<template>
  <el-dialog title="新增品牌" v-model="addDialogVisible" width="30%" destroy-on-close>
    <el-form style="width: 80%" :model="trademarkParams" :rules="rules" ref="formRef">
      <el-form-item label="品牌名称:" label-width="100px" prop="tmName">
        <el-input placeholder="请您输入品牌名称" v-model="trademarkParams.tmName"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO:" label-width="100px" prop="logoUrl">
        <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage, UploadProps } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import type { TradeMark } from '@/api/product/trademark/type';
import { reqAddOrUpdateTrademark } from '@/api/product/trademark';
let props = defineProps({
  info: {
    type: Object,
    default: {},
  },
});
const updateInfo = defineEmits(['update']);
let addDialogVisible = ref(false);

let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
});

watch(
  () => props.info.id,
  (newval) => {
    if (newval) return Object.assign(trademarkParams, props.info);
    trademarkParams = reactive<TradeMark>({
      tmName: '',
      logoUrl: '',
    });
  },
);
//品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  //如果图片上传
  if (value) {
    callBack();
  } else {
    callBack(new Error('LOGO图片务必上传'));
  }
};

// 获取el-form组件实例
let formRef = ref<FormInstance>();
let rules = reactive<FormRules>({
  tmName: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
});

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M',
      });
      return false;
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必PNG|JPG|GIF',
    });
    return false;
  }
};

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // /response:即为当前这次上传图片post请求服务器返回的数据
  //收集上传图片的地址,添加一个新的品牌的时候带给服务器
  console.log(response);

  trademarkParams.logoUrl = response.data;
  //图片上传成功,清除掉对应图片校验结果
  console.log(trademarkParams);
  formRef.value?.clearValidate('logoUrl');
};

const confirm = async () => {
  await formRef.value?.validate(async (isValid) => {
    if (!isValid) return;
    let result: any = await reqAddOrUpdateTrademark(trademarkParams);
    if (result.code === 200) {
      //关闭对话框
      addDialogVisible.value = false;
      close();
      //弹出提示信息
      ElMessage({
        type: 'success',
        message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
      });
    } else {
      //添加品牌失败
      ElMessage({
        type: 'error',
        message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
      });
      //关闭对话框
      addDialogVisible.value = false;
      close();
    }
    updateInfo('update');
  });
};

const close = () => {
  addDialogVisible.value = false;
  formRef.value?.clearValidate('tmName');
  formRef.value?.clearValidate('logoUrl');
};

const open = () => {
  addDialogVisible.value = true;
};

defineExpose({
  open,
});
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
